package com.wzy.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 描述
 * 创建人    Wzy
 * 创建时间: 2020-05-20  19:59
 */
public class NIOServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //得到一个selector对象

        Selector selector = Selector.open();

        //绑定5555端口
        serverSocketChannel.socket().bind(new InetSocketAddress(5555));

        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);

        //把serverSocketChannel 注册到selector 关心事件为OP_ACCEPT 连接时间
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        //循环等待
        while (true) {
            //等待一秒,如果没有连接时发就
            if (selector.select(1000) == 0) {
                System.out.println("服务器等待1s,无连接");
                continue;
            }
            //如果返回的不是0,获取到相关的selectionKey集合
            //1.如果返回的>0,表示已经获取到关注的事件
            //2. selector.selectedKeys(),返回的是关注事件的集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            //遍历集合
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                //获取到selectionKey
                SelectionKey key = iterator.next();
                //根据这个key  对应的通道发生的时间 做响应的处理
                if (key.isAcceptable()) {
                    //说明响应 OP_ACCEPT
                    //给该客户端生成一个socketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端成功连接 生成了一个socketChannel:" + socketChannel.hashCode());
                    //将SocketChannel 设置为非阻塞
                    socketChannel.configureBlocking(false);
                    //将当前的socketChannel注册到selector,关注事件SelectionKey.OP_READ,同时
                    //给socketChannel 关联一个buffer
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (key.isReadable()) {
                    //发生OP_READ
                    //通过key,反向获得socketChannel
                    SocketChannel channel = (SocketChannel) key.channel();
                    //获取到该channel关联的buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();

                    channel.read(buffer);
                    System.out.println("from客户端" + new String(buffer.array()));

                }
                //手动从集合中移动当前的selectionKey,防止重复操作
                iterator.remove();
            }
        }
    }
}
